/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.network.tcp;

import java.io.IOException;
import java.net.URI;

import org.latestbit.smartobjects.exceptions.IncorrectURIException;
import org.latestbit.smartobjects.network.IAcceptor;
import org.latestbit.smartobjects.network.IConnector;
import org.latestbit.smartobjects.network.IHandshakeManagerFactory;
import org.latestbit.smartobjects.network.INetworkFactory;
import org.latestbit.smartobjects.network.IPacketFormerFactory;

public class TCPFactory implements INetworkFactory {
	
	private TCPSharedResources resources = new TCPSharedResources();
	
	private TCPSharedResources getResources() {		
		return resources;
	}
	
	@Override
	public IAcceptor createAcceptor(URI location) throws IncorrectURIException, IOException {
		IAcceptor acceptor = createAcceptor();
		acceptor.setEndpointURI(location);
		return acceptor;
	}
	
	@Override
	public IAcceptor createAcceptor() throws IncorrectURIException, IOException {
		return new TCPAcceptor(getResources());
	}

	@Override
	public IConnector createConnector(URI location)
			throws IncorrectURIException, IOException {
		IConnector connector = createConnector();
		connector.setEndpointURI(location);
		return connector;
	}

	@Override
	public IConnector createConnector() throws IncorrectURIException,
			IOException {
		TCPConnector result = new TCPConnector(getResources());		
		return result;
	}

	@Override
	public void destroy() {
		/* if(resources!=null)
			resources.destroy(); */
		if(resources!=null) {
			resources.release();
			resources = null;
		}
	}
	
	public void finalize() {
		destroy();
	}

	@Override
	public IHandshakeManagerFactory getHandshakeManagerFactory() {		
		return resources.getHandshakeManagerFactory();
	}

	@Override
	public IPacketFormerFactory getPacketFormerFactory() {
		return resources.getPacketFormerFactory();
	}

	@Override
	public void setHandshakeManagerFactory(IHandshakeManagerFactory factory) {
		this.resources.setHandshakeManagerFactory( factory );
	}

	@Override
	public void setPacketFormerFactory(IPacketFormerFactory factory) {
		this.resources.setPacketFormerFactory( factory );
	}


}
